package com.ssttevee.taskmanagerapp.services;

import java.io.IOException;
import com.ssttevee.taskmanagerapp.TaskManagerApplication;
import com.ssttevee.taskmanagerapp.ViewServersActivity.ResponseReceiver;
import com.ssttevee.taskmanagerapp.tasks.ServerQuery;
import com.ssttevee.taskmanagerapp.tasks.Task;

import android.app.IntentService;
import android.content.Intent;

public class RefreshServers extends IntentService {
	
	private TaskManagerApplication app;
	public static final String GETTING_MESSAGE = "position_and_id";
	public static final String RETURNING_MESSAGE = "returning_message";
	public static final String REPOLL_COOLDOWN_FINISH = "repoll_cooldown_fin";

	public RefreshServers() {
		super("RefreshServers");
	}

	@Override
	protected void onHandleIntent(Intent intent) {

		int[] i = intent.getIntArrayExtra(GETTING_MESSAGE);
        
		app = (TaskManagerApplication) getApplication();
		Task t = app.getTaskById((int) i[1]);
		
		ServerQuery sq = new ServerQuery();
		if(t.getGs4Port() > 0) {
			try {
				sq.queryServer(t);
				sq.pollServer(t);
			} catch (IOException e) {
			}
		} else {
			try {
				sq.pollServer(t);
			} catch (IOException e) {
			}
		}

    	t.setMotd(sq.getMotd());
    	t.setMaxPlayers(sq.getMaxPlayers());
    	t.setOnlinePlayers(sq.getPlayerCount());
    	t.setPlayers(sq.getPlayers());
    	t.setOnline(sq.isOnline());
    	t.setLatency(sq.getLatency());
    	t.setVersion(sq.getVersion());
    	t.setTimesOnline(t.getTimesOnline() + (sq.isOnline() ? 1 : 0));
    	t.setTimesChecked(t.getTimesChecked() + 1);
    	
		app = (TaskManagerApplication) getApplication();
		app.saveTask(t);
        
        Intent broadcastIntent = new Intent();
        broadcastIntent.setAction(ResponseReceiver.ACTION_RESP);
        broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
        broadcastIntent.putExtra(RETURNING_MESSAGE, i);
        sendBroadcast(broadcastIntent);
	}

}
